package com.ext.aic.adapter.binder;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;

import com.ext.aic.R;
import com.ext.aic.beans.CompanyItem;
import com.ext.aic.beans.FlowItem;
import com.ext.aic.events.ViewTypeBinder;
import com.ext.aic.holder.IndustryEnterpriseListViewHolder;
import com.ext.aic.handler.FlowHandler;
import com.ext.aic.utils.ToastyUtils;
import com.eyinfo.android_pure_utils.utils.ObjectJudge;
import com.eyinfo.android_pure_utils.utils.StartUtils;
import com.google.android.flexbox.FlexboxLayout;

import java.util.ArrayList;
import java.util.List;

public class IndustryEnterpriseListItemBinder implements ViewTypeBinder<IndustryEnterpriseListViewHolder, CompanyItem> {

    private Context context;

    public IndustryEnterpriseListItemBinder(Context context) {
        this.context = context;
    }

    @Override
    public void bind(IndustryEnterpriseListViewHolder holder, CompanyItem companyItem, int position) {
        holder.enterpriseTv.setText(companyItem.getName());
        bindLabels(companyItem, holder.labelFbl);
        holder.telTv.setText(companyItem.getPhone());
        holder.addressTv.setText(companyItem.getAddress());

        holder.telIv.setTag(companyItem);
        holder.telIv.setOnClickListener(this::onTelClick);
        holder.copyIv.setTag(companyItem);
        holder.copyIv.setOnClickListener(this::onCopyClick);
    }

    private CompanyItem getCompanyByTag(View view) {
        Object tag = view.getTag();
        if (!(tag instanceof CompanyItem)) {
            return null;
        }
        return (CompanyItem) tag;
    }

    public void onCopyClick(View view) {
        CompanyItem companyItem = getCompanyByTag(view);
        if (TextUtils.isEmpty(companyItem.getPhone())) {
            return;
        }
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("tel:", companyItem.getPhone());
        clipboard.setPrimaryClip(clip);
        ToastyUtils.getInstance().show(context.getString(R.string.copy_tel_success));
    }

    public void onTelClick(View view) {
        CompanyItem companyItem = getCompanyByTag(view);
        if (TextUtils.isEmpty(companyItem.getPhone())) {
            return;
        }
        StartUtils.getInstance().startTel(view.getContext(), companyItem.getPhone());
    }

    private void bindLabels(CompanyItem companyItem, FlexboxLayout labelFbl) {
        List<String> labels = companyItem.getTags();
        if (ObjectJudge.isNullOrEmpty(labels)) {
            return;
        }
        List<FlowItem> tabItems = new ArrayList<>();
        for (String label : labels) {
            tabItems.add(new FlowItem(label));
        }
        FlowHandler flowHandler = new FlowHandler();
        flowHandler.bindTags(labelFbl, tabItems);
    }
}
